<?php

namespace Yolo\Logs;

use Yolo\Di\Annotations\Singleton;
use Yolo\Utils\DateTime;

#[Singleton]
class FileLog implements LogInterface
{

    /**
     * @psalm-param array{
     *     action: string,
     *     message: string,
     *     data?: array<string, mixed>
     * } $log
     * @param array $log
     * @return void
     */
    public function debug(array $log): void
    {
        $this->writeLog(json_encode($log, JSON_UNESCAPED_UNICODE), 'debug');
    }

    public function info(array $log): void
    {
        $this->writeLog(json_encode($log, JSON_UNESCAPED_UNICODE), 'info');
    }

    public function warn(array $log): void
    {
        $this->writeLog(json_encode($log, JSON_UNESCAPED_UNICODE), 'warning');
    }

    public function error(array $log): void
    {
        $this->writeLog(json_encode($log, JSON_UNESCAPED_UNICODE), 'error');
    }

    private function getLogFilePath(): string
    {
        return BASE_PATH . '/storage/logs/hyperf-' . date('Y-m-d') . '.log';
    }

    private function writeLog(string $message, string $level): void
    {
        file_put_contents($this->getLogFilePath(), '[' . DateTime::getCurrentDateTimeWithMs() . "][$level] " . $message . PHP_EOL, FILE_APPEND);
    }
}